﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MindFactorial.LaunchPoint.Console.Library;
using MindFactorial.LaunchPoint.Runtime;
using MindFactorial.LaunchPoint.Common;
using System.Threading;
using System.Windows.Threading;

namespace MindFactorial.LaunchPoint.Console
{
    /// <summary>
    /// Interaction logic for SplashScreen.xaml
    /// </summary>
    public partial class SplashScreen
    {
        System.Threading.ThreadStart _initialize_callback;
        DispatcherTimer _request_timer = null;
        int _stop_count = 20;

        public SplashScreen(System.Threading.ThreadStart initialize_callback)
        {
            InitializeComponent();
            this._initialize_callback = initialize_callback;

            
            _request_timer = new DispatcherTimer();
            _request_timer.Tick += (sender, e) =>
            {
                if (_stop_count > 0)
                {
                    _stop_count--;

                    //set value to half of availabel space (just to make the progress bar move)
                    progress.Value = progress.Maximum - ((progress.Maximum - progress.Value) / 2);
                }
                else
                {
                    MessageBox.Show("Could not initialize in a timely manner", "29F6F1F2-F7A9-4b76-B213-EDC2F1FE7DE2");
                    this.DialogResult = false;
                }
            };
            _request_timer.Interval = TimeSpan.FromSeconds(1);
            progress.Maximum = 100;
            progress.MinWidth = 0;
            progress.Value = 0;
            
            this.Loaded += new RoutedEventHandler(SplashScreen_Loaded);
            
        }

        void SplashScreen_Loaded(object sender, RoutedEventArgs e)
        {
            //increase progress bar value
            progress.Value = 2;

            //start the request timer
            _request_timer.Start();

            try
            {
                
                Dispatcher.Invoke(DispatcherPriority.Background, _initialize_callback);
                this.DialogResult = true;
                _request_timer.Stop();
                this.Close();
            }
            catch (Exception ex)
            {
                this.DialogResult = false;
                this.Close();
            }

            

        }
    }
}
